package com.wbtech.ums.performance;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import com.wbtech.ums.AppInfo;
import com.wbtech.ums.CobubLog;
import com.wbtech.ums.CommonUtil;
import com.wbtech.ums.DeviceInfo;
import com.wbtech.ums.MyMessage;
import com.wbtech.ums.NetworkUtil;
import com.wbtech.ums.UmsAgent.SendPolicy;
import com.wbtech.ums.UmsConstants;

public class FpsWorker extends Thread {

	private Context mContext;
	private BlockingQueue<ArrayList<FpsRecord>> mRecordQueue = new LinkedBlockingQueue<ArrayList<FpsRecord>>();
	private DecimalFormat mFpsFormat = new DecimalFormat("0.0");

	private boolean mQuit = false;
	private static final String tag = "FpsWorker";
	private static final String FPS_URL = "/ums/postFpslog";

	private StringBuilder sb;
	private String averageFps;
	private String time; // 测试结束的时间

	JSONObject uploadObject; // 最终上传的JSONObject
	JSONArray fpsArray;
	JSONObject fpsObject;

	public FpsWorker(Context context,
			BlockingQueue<ArrayList<FpsRecord>> recordQueue) {
		this.mContext = context;
		this.mRecordQueue = recordQueue;
	}

	public void quit() {
		mQuit = true;
	}

	private void prepareFpsJson(String fpsValues, String avgFps)
			throws JSONException {

		uploadObject = new JSONObject(); // 最终上传的JSONObject
		fpsArray = new JSONArray();
		fpsObject = new JSONObject();

		fpsObject.put("version", AppInfo.getAppVersion());
		fpsObject.put("device", DeviceInfo.getDeviceName());
		fpsObject.put("os_version", DeviceInfo.getOsVersion());
		fpsObject.put("fpsValues", fpsValues);
		fpsObject.put("avgFps", avgFps);
		String appKey = AppInfo.getAppKey();
		fpsObject.put("appkey", appKey);
		fpsObject.put("time", time);

		fpsArray.put(fpsObject);
		uploadObject.put("appkey", appKey);
		uploadObject.put("fpsInfo", fpsArray);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();

		while (!mQuit) {
			ArrayList<FpsRecord> records = null;
			try {
				records = mRecordQueue.take();
			} catch (InterruptedException e) {
				continue;
			}

			// 记录每次的值
			sb = new StringBuilder();
			long totalFps = 0l;
			final int size = records.size();
			for (int i = 0; i < size; ++i) {
				FpsRecord record = records.get(i);
				totalFps += record.mFps;
				sb.append(mFpsFormat.format(record.mFps));
				sb.append(",");
			}

			// 平均值
			double avgFps = totalFps / size;
			averageFps = mFpsFormat.format(avgFps);

			time = DeviceInfo.getDeviceTime(); // 执行结束的时间

			records.clear();

			try {
				prepareFpsJson(sb.toString(), averageFps);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				CobubLog.e(tag, e);
				return;
			}

			if (CommonUtil.getReportPolicyMode(mContext) == SendPolicy.REALTIME
					& CommonUtil.isNetworkAvailable(mContext)) {
				String result = NetworkUtil.Post(UmsConstants.urlPrefix
						+ FPS_URL, uploadObject.toString());
				MyMessage message = NetworkUtil.parse(result);
				if (message == null) {
					CommonUtil.saveInfoToFile("fpsInfo", fpsObject,
							"/fps.cache", mContext);
					return;
				}

				if (message.getFlag() < 0) {
					CobubLog.e(tag, "Error Code=" + message.getFlag()
							+ ",Message=" + message.getMsg());
					if (message.getFlag() == -4)
						CommonUtil.saveInfoToFile("fpsInfo", fpsObject,
								"/fps.cache", mContext);
				}
			} else {
				CommonUtil.saveInfoToFile("fpsInfo", fpsObject, "/fps.cache",
						mContext);
			}
		}
	}

}
